from flask import Flask, request, jsonify,Blueprint
import os
app = Flask(__name__)
dify_blueprint = Blueprint('dify', __name__)

def load_sensitive_words():
    sensitive_words = []
    try:
        # 获取当前文件的绝对路径
        current_dir = os.path.dirname(os.path.abspath(__file__))
        # 构建敏感词文件的绝对路径
        sensitive_file_path = os.path.join(os.path.dirname(current_dir), 'static', '敏感词.txt')
        with open(sensitive_file_path, 'r', encoding='utf-8') as file:
            sensitive_words = [line.strip() for line in file.readlines()]
    except FileNotFoundError:
        print("敏感词文件未找到，请确认文件存在。")
    return set(sensitive_words)  # 使用set提高查找效率
sensitive_words_set = load_sensitive_words()


def handle_input(params):
    # 这里可以加入针对输入的具体处理逻辑
    query = params.get("query", "")
    # 检查query是否包含敏感词
    flagged = any(word in query for word in sensitive_words_set)
    
    if flagged:
        return {
            "flagged": True,
            "action": "direct_output",
            "preset_response": "您好，您的输入包含不支持的内容。我们换个话题吧"
        }
    else:
        return {
            "flagged": False,
            "action": "direct_output",
            "preset_response": ""
        }

def handle_output(params):
    # 这里可以加入针对输入的具体处理逻辑
    query = params.get("text", "")
    # 检查query是否包含敏感词
    flagged = any(word in query for word in sensitive_words_set)
    
    if flagged:
        return {
            "flagged": True,
            "action": "direct_output",
            "preset_response": "您好，输出包含不支持的内容。我们换个话题吧"
        }
    else:
        return {
            "flagged": False,
            "action": "direct_output",
            "preset_response": ""
        }

@dify_blueprint.route('/moderation', methods=['POST'])
def moderation():
    print("a")
    data = request.json
    print(data)
    point = data.get("point")
    
    print(point)
    
    params = data.get("params", {})
    if point == 'ping':
        return {"result": "pong"}
    if point == "app.moderation.input":
        # 确保params包含必要的键
        required_keys = {"app_id", "inputs", "query"}
        if not all(key in params for key in required_keys):
            return jsonify({"error": "Missing required keys in params for app.moderation.input"}), 400
        result = handle_input(params)
    elif point == "app.moderation.output":
        # 确保params包含必要的键
        required_keys = {"app_id", "text"}
        if not all(key in params for key in required_keys):
            return jsonify({"error": "Missing required keys in params for app.moderation.output"}), 400
        result = handle_output(params)
    
    return jsonify(result)

